package com.gym.myshop.services.impl;

import com.gym.myshop.common.Const;
import com.gym.myshop.dao.CartDao;
import com.gym.myshop.dao.ItemDao;
import com.gym.myshop.dao.OrderDao;
import com.gym.myshop.dao.impl.CartDaoImpl;
import com.gym.myshop.dao.impl.ItemDaoImpl;
import com.gym.myshop.dao.impl.OrderDaoImpl;
import com.gym.myshop.entity.Cart;
import com.gym.myshop.entity.Item;
import com.gym.myshop.entity.Orders;
import com.gym.myshop.services.OrderServices;
import com.gym.myshop.util.DBUtil;
import com.gym.myshop.util.RandomUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ming
 * 2021/11/8
 * description:订单
 */
public class OrderServicesImpl implements OrderServices {

    private OrderDao od = new OrderDaoImpl();
    private CartDao cd = new CartDaoImpl();//购物车
    private ItemDao id = new ItemDaoImpl();


    /**
     *@author:ming
     *@Date: 2021/11/8
     *@description:生成订单
     * aid地址实体的唯一主键列  uid用户实体的主键属性
     */
    @Override
    public Orders createOrder(Integer aid, int uid) {
        try {
            DBUtil.begin();
            //创建order对象进行数据的赋值
            Orders o = new Orders();
            //设置订单的编号,该数据主键为varchar,没有自增
            o.setOid(RandomUtils.createOrderId());
            //设置订单生成时间
            o.setOtime(new Date());
            o.setAid(aid);
            o.setUid(uid);
            //刚生成的订单设置为未支付状态
            o.setOstate(Const.OrderCode.NOT_PAY);
            //获取购物车数据
            List<Cart> carList = cd.getCarList(uid);
            double sum = 0;
            //创建itemLIst用于转存购物车的数据
            List<Item> itemList = new ArrayList<>();
            for (Cart cart : carList) {
                //计算总金额
                sum += cart.getCcount();
                Item i = new Item();
                i.setInum(cart.getCnum());
                //设置订单编号, 外键连购物车
                i.setOid(o.getOid());
                i.setIcount(cart.getCcount());
                i.setPid(cart.getPro().getPid());
                itemList.add(i);
            }
            //设置订单总金额
            o.setOcount(sum);
            //要先进行oerder数据的新增
            od.addOrder(o);
            //进行item批量的新增
            id.addItems(itemList);
            //清空购物车的数据
            cd.clearCart(uid);
            DBUtil.commit();
            return o;
        } catch (SQLException e) {
            e.printStackTrace();
            DBUtil.rollback();
        }
        return null;
    }

    /**
     *@author:ming
     *@Date: 2021/11/8
     *@description:获取订单列表信息
     * uid用户实体的主键属性
     */
    @Override
    public List<Orders> getOrderList(int uid) {
        try {
            DBUtil.begin();
            List<Orders> ordersList = od.getOrderList(uid);
            DBUtil.commit();
            return ordersList;
        } catch (Exception e) {
            e.printStackTrace();
            DBUtil.rollback();
        }
        return null;
    }
}
